<?php

namespace app\api\controller;

use app\common\controller\Api;
use Exception;
use \think\exception\PDOException;
use think\Db;
use app\api\controller\Config;
use app\admin\model\test\Test as TestModel;

/**
 * 首页接口
 */
class Yjgl extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     */
    public function index()
    {
        $this->success('yjgl:请求成功');
    }
    //-------------------------------------------全局-------------------------------------------------------
    /***
     * 获取全局信息
     * 用户基本信息:姓名、电话、积分、单位
     * 获取学习页tablist
     * 
     */
    public function getGlobalData()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        if (!($mobile)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            //用户信息
            $sql = "SELECT id as articleId, username,mobile,score,merchant_name FROM `fa_user` 
                LEFT JOIN fa_merchant on fa_user.merchant_id = fa_merchant.merchant_id
                WHERE fa_user.mobile ='$mobile'";
            $userRes = Db::query($sql);
            if (count($userRes) == 0) {
				return $this->success("没有该用户", null, 400);
            }
            $data["userInfo"] = $userRes[0];

            //分类列表
            $sql = "SELECT id,title as name FROM `fa_article_category`";
            $categoryRes = Db::query($sql);
            $data["categorydata"] = $categoryRes;
            return $this->success("success", $data, 200);
        } catch (PDOException $e) {
            return $this->success("获取全局信息出错" . $e->getMessage(), null, 500);
        }
    }

    //-------------------------------------------首页-------------------------------------------------------
    //获取首页信息列表
    public function getIndexData()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        if (!($mobile)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            $prefix = "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];
            //获取企业列表
            $sql = "SELECT merchant_id, merchant_name , merchant_tel, address,abbr,
                 REPLACE(merchant_image,'/uploads','{$prefix}/uploads') as merchant_image
             FROM fa_merchant";
            $merchantRes = Db::query($sql);
            $data["merchant"] = $merchantRes;

            $sql = "SELECT id as articleId, label,title,views, FROM_UNIXTIME(updatetime) as updateTime,FROM_UNIXTIME(fa_article.createtime) as createTime,fa_article.desc,merchant_name,
            REPLACE(content," .  "'<img src=\"'," . "'<img src=\"" . $prefix . "') as content,
            REPLACE(layout_image,'/uploads','{$prefix}/uploads') as layout_image,
            REPLACE(image,'/uploads','{$prefix}/uploads') as small_image
            FROM `fa_article`
            LEFT JOIN fa_merchant on fa_article.merchant_id = fa_merchant.merchant_id
            WHERE label='曝光'";
            $exposureRes = Db::query($sql);
            $data["exposuredata"] = $exposureRes;
            
            return $this->success("success", $data, 200);
        } catch (PDOException $e) {
            return $this->success("获取首页信息列表出错" . $e->getMessage(), null, 500);
        }
    }

    //获取企业信息列表
    public function getMerchant()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        if (!($mobile)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            $prefix = "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];
            $sql = "SELECT merchant_name , merchant_tel, address,abbr,
                REPLACE(merchant_image,'/uploads','{$prefix}/uploads') as merchant_image
            FROM fa_merchant";
            $merchantRes = Db::query($sql);
            $data["merchant"] = $merchantRes;
            return $this->success("success", $data, 200);
        } catch (PDOException $e) {
            return $this->success("获取企业列表出错" . $e->getMessage(), null, 500);
        }
    }

    //获取曝光台数据
    public function getExposureData()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        $prefix = "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];
        if (!($mobile)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            $sql = "SELECT label,title,views, FROM_UNIXTIME(updatetime) as updateTime,FROM_UNIXTIME(fa_article.createtime) as createTime,fa_article.desc,merchant_name,
            REPLACE(content," .  "'<img src=\"'," . "'<img src=\"" . $prefix . "') as content,
            REPLACE(layout_image,'/uploads','{$prefix}/uploads') as layout_image,
            REPLACE(image,'/uploads','{$prefix}/uploads') as small_image
            FROM `fa_article`
            LEFT JOIN fa_merchant on fa_article.merchant_id = fa_merchant.merchant_id
            WHERE label='曝光'";
            $sqlRes = Db::query($sql);
            $data["exposuredata"] = $sqlRes;
            return $this->success("success", $data, 200);
        } catch (PDOException $e) {
            return $this->success("获取曝光台数据出错" . $e->getMessage(), null, 500);
        }
    }

    //-------------------------------------------用户-------------------------------------------------------
    //获取用户信息
    public function login()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        $password = $params["password"] ?? null;
        if (!($mobile && $password)) {
            return $this->success("请输入账号密码", null, 400);
        }
        try {
            $sql = "SELECT password,salt FROM fa_user
                WHERE mobile='$mobile'";
            $sqlRes = Db::query($sql);
            if (count($sqlRes) == 0) {
				return $this->success("没有该用户", null, 400);
            }
            
            $pwd = $sqlRes[0]["password"];
            $salt = $sqlRes[0]["salt"];
            if (md5(md5($password) . $salt) != $pwd) {
                return $this->success("密码错误", null, 400);
            } 
            return $this->success("登录成功", null, 200);
        } catch (PDOException $e) {
            return $this->success("登录出错" . $e->getMessage(), null, 500);
        }
    }

    public function getUserInfo()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        if (!($mobile)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            $sql = "SELECT username,mobile,score,merchant_name FROM `fa_user` 
            LEFT JOIN fa_merchant on fa_user.merchant_id = fa_merchant.merchant_id
            WHERE fa_user.mobile ='$mobile'";
            $userRes = Db::query($sql);
            if (count($userRes) == 0) {
				return $this->success("没有该用户", null, 400);
            }
            $data["userInfo"] = $userRes[0];
            return $this->success("success", $data, 200);
        } catch (PDOException $e) {
            return $this->success("获取用户信息出错" . $e->getMessage(), null, 500);
        }
    }


    //-------------------------------------------学习-------------------------------------------------------
    //获取新闻列表
    public function getStudyData()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        if (!($mobile)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            $prefix = "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];
            //用户信息
            $sql = "SELECT username,mobile,score,merchant_name FROM `fa_user` 
                LEFT JOIN fa_merchant on fa_user.merchant_id = fa_merchant.merchant_id
                WHERE fa_user.mobile ='$mobile'";
            $userRes = Db::query($sql);
            if (count($userRes) == 0) {
				return $this->success("没有该用户", null, 400);
            }
            $data["userInfo"] = $userRes[0];

            //分类列表
            $sql = "SELECT id,title as name FROM `fa_article_category` ORDER BY weigh desc";
            $categoryRes = Db::query($sql);
            $data["categorydata"] = $categoryRes;

            return $this->success("success", $data, 200);
        } catch (PDOException $e) {
            return $this->success("获取新闻列表出错" . $e->getMessage(), null, 500);
        }
    }

    // 获取文章列表
    public function getArticleListById()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        $index = $params["index"] ?? null;
        $currentPage = $params["currentPage"] ?? null;
        $limit = $currentPage * 10;

        if (!($mobile)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            $prefix = "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

            //分类列表
            $sql = "SELECT id,title as name FROM `fa_article_category` ORDER BY weigh desc";
            $categoryRes = Db::query($sql);
            $data["categorydata"] = $categoryRes;
            $categoryId = $categoryRes[$index]["id"];

            //新闻数据(分类)
            $sql = "SELECT count(*) as total
                    FROM `fa_article`
                    LEFT JOIN fa_merchant on fa_article.merchant_id = fa_merchant.merchant_id
                    WHERE category_id='$categoryId'";
            $totalRes = Db::query($sql);
            $totalPage = ceil($totalRes[0]["total"] / 10);

            $sql = "SELECT id as articleId, type, label,title,views,fa_article.desc,merchant_name,
                FROM_UNIXTIME(updatetime) as updateTime,FROM_UNIXTIME(fa_article.createtime) as createTime,
                REPLACE(layout_image,'/uploads','{$prefix}/uploads') as layout_image,
                REPLACE(image,'/uploads','{$prefix}/uploads') as small_image,
                REPLACE(video,'/uploads','{$prefix}/uploads') as video, 
                REPLACE(video_cover,'/uploads','{$prefix}/uploads') as video_cover
                FROM `fa_article`
                LEFT JOIN fa_merchant on fa_article.merchant_id = fa_merchant.merchant_id
                WHERE category_id='$categoryId' ORDER BY createtime desc
                limit $limit, 10";
            $newsDataRes = Db::query($sql);
            $data["newsdata"] = $newsDataRes;
            $data["totalPage"] = $totalPage;
            return $this->success("success", $data, 200);
        } catch (PDOException $e) {
            return $this->success("获取文章列表出错" . $e->getMessage(), null, 500);
        }
    }

     // 获取企业课堂列表
     public function getEnterpriseArticles()
     {
         $params = $this->request->param();
         $mobile = $params["mobile"] ?? null;
         $articleType = $params["articleType"] ?? null;
         $merchantId = $params["merchantId"] ?? null;
         if (!($mobile)) {
             return $this->success("参数不全", null, 400);
         }
         try {
            $prefix = "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

            if ($articleType == "公共课堂") {
                $sql = "SELECT id as articleId, type, label,title,views,fa_article.desc,merchant_name,
                    FROM_UNIXTIME(updatetime) as updateTime,FROM_UNIXTIME(fa_article.createtime) as createTime,
                    REPLACE(layout_image,'/uploads','{$prefix}/uploads') as layout_image,
                    REPLACE(image,'/uploads','{$prefix}/uploads') as small_image,
                    REPLACE(video,'/uploads','{$prefix}/uploads') as video, 
                    REPLACE(video_cover,'/uploads','{$prefix}/uploads') as video_cover
                    FROM `fa_article`
                    LEFT JOIN fa_merchant on fa_article.merchant_id = fa_merchant.merchant_id
                    WHERE label='$articleType' ORDER BY createtime desc";
                $newsDataRes = Db::query($sql);
                $data["newsdata"] = $newsDataRes;

                return $this->success("success", $data, 200);
            } elseif($articleType == "企业课堂") {
                $sql = "SELECT id as articleId, type, label,title,views,fa_article.desc,merchant_name,
                    FROM_UNIXTIME(updatetime) as updateTime,FROM_UNIXTIME(fa_article.createtime) as createTime,
                    REPLACE(layout_image,'/uploads','{$prefix}/uploads') as layout_image,
                    REPLACE(image,'/uploads','{$prefix}/uploads') as small_image,
                    REPLACE(video,'/uploads','{$prefix}/uploads') as video, 
                    REPLACE(video_cover,'/uploads','{$prefix}/uploads') as video_cover
                    FROM `fa_article`
                    LEFT JOIN fa_merchant on fa_article.merchant_id = fa_merchant.merchant_id
                    WHERE label='$articleType' and fa_article.merchant_id = '$merchantId' ORDER BY createtime desc";
                $newsDataRes = Db::query($sql);
                $data["newsdata"] = $newsDataRes;

                return $this->success("success", $data, 200);
            } else{
                return $this->success("课堂类型不存在",null, 400);
            }

         } catch (PDOException $e) {
             return $this->success("获取企业课堂出错" . $e->getMessage(), null, 500);
         }
     }

    // 获取文章详情
    public function getArticleById()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        $articleId = $params["articleId"] ?? null;
        if (!($mobile && $articleId)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            $prefix = "http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER["SERVER_PORT"];

            $sql = "SELECT fa_article.id, fa_article.title, fa_article.desc,fa_article.type, fa_test.id as testId,
                REPLACE(video,'/uploads','{$prefix}/uploads') as video, 
                REPLACE(content," .  "'<img src=\"'," . "'<img src=\"" . $prefix . "') as content
                FROM `fa_article`
                LEFT JOIN fa_test on fa_article.id = fa_test.article_id
                WHERE fa_article.id='$articleId'";
            $articleRes = Db::query($sql);
            return $this->success("success", $articleRes[0], 200);
        } catch (PDOException $e) {
            return $this->success("获取文章出错" . $e->getMessage(), null, 500);
        }
    }
    
    // 获取文章对应的试卷
    public function getTestById()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        $testId = $params["testId"] ?? null;
        if (!($mobile && $testId)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            $sql = "SELECT ib.*
                FROM fa_test_item as ti
                LEFT JOIN fa_test as t on t.id = ti.test_id
                LEFT JOIN fa_itembank as ib on ti.item_id = ib.id
                WHERE t.id=$testId";
            $testRes = Db::query($sql);
            return $this->success("success", $testRes, 200);
        } catch (PDOException $e) {
            return $this->success("获取试卷出错" . $e->getMessage(), null, 500);
        }
    }

    // 每天阅读文章 获取积分
    public function addScoreByArticle()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        $articleId = $params["articleId"] ?? null;
        $dateInfo = $params["dateInfo"] ?? null;
        if (!($mobile && $articleId && $dateInfo)) {
            return $this->success("参数不全", null, 400);
        }
        Db::startTrans();
        try {
            // 获取文章的积分
            $sql = "select score from fa_article where id='$articleId'";
            $res = Db::query($sql);
            if(!count($res)){
                $this->success("文章不存在", null, 400);
            }
            $score = $res[0]['score'];
            // 给用户加分
            $scoreRes = $this->_addUserScore($mobile,$score,$articleId,$dateInfo,"文章");
            if ($scoreRes["code"] == 200) {
                $sql = "select score from fa_user where mobile='$mobile'";
                $sqlRes = Db::query($sql);
                Db::commit();
                return $this->success("success", $sqlRes, 200);
            }
            Db::rollback();
            return $this->success("fail", null, 400);
        } catch (PDOException $e) {
            Db::rollback();
            return $this->success("阅读文章加积分出错" . $e->getMessage(), null, 500);
        }
    }

    // 增加用户积分：（阅读文章/答题 均可获取积分）
    private function _addUserScore($mobile, $score, $businessNumber, $dateInfo,$type)
    {
        try {
            $sql = "select * from fa_user_score_record 
                where mobile='$mobile' and businessnumber='$businessNumber' and dateinfo='$dateInfo'";
            $scoreRes = Db::query($sql);
            if (count($scoreRes)==0) {
                # 当天没有记录，则加 积分
                $item = "";
                if ($type == '答题') {
                    $sql = "select title from fa_test where id='$businessNumber'";
                    $res = Db::query($sql);
                    $item = count($res) ? $res[0]['title'] : "";
                } elseif( $type == '文章'){
                    $sql = "select title from fa_article where id='$businessNumber'";
                    $res = Db::query($sql);
                    $item = count($res) ? $res[0]['title'] : "";
                }

                $sql = "insert into fa_user_score_record(mobile,item,itemtype,businessnumber,score,dateinfo,createtime)
                        values('$mobile','$item','$type','$businessNumber','$score','$dateInfo',unix_timestamp(now()))";
                Db::execute($sql);
                $sql = "update fa_user set score=score+$score where mobile='$mobile'";
                Db::execute($sql);
            }
            // 当天有记录了，直接返回
            $ret["code"] = 200;
            $ret["msg"] = "success";
            return $ret;
        } catch (PDOException $e) {
            $ret["code"] = 500;
            $ret["msg"] = $e->getMessage();
            return $ret;
        }
    }

    // 检查试卷答案
    public function checkTestAnswer()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        $testId = $params["testId"] ?? null;
        $answerList = $params["answerList"] ?? null;
        $dateInfo = $params["dateInfo"] ?? null;
        if (!($mobile && $testId && $answerList && $dateInfo)) {
            return $this->success("参数不全", null, 400);
        }

        Db::startTrans();
        try {
            //获取该试卷信息
            $testInfo = TestModel::getTestDetail($testId,true);
            if(empty($testInfo)){
                $this->success("试卷不存在", null, 400);
            }

            //循环检测
            $answers = [];
            $total_score = 0;
            $total_right = 0;
            $total_noanswer = 0;
            foreach($testInfo['itemList'] as $key=>$val){
                $answers[$key]['item_id'] = $val['item_id'];
                $answers[$key]['type'] = $val['itembank']['type'];
                if(isset($answerList[$key]['id'])){
                    // 单选，多选 都按照多选处理
                    $answer_arr = explode(",",$val['itembank']['answer']);
                    $user_answer_arr = explode(",",$answerList[$key]['answerList']);
                    $result = array_intersect($answer_arr,$user_answer_arr);
                    $answers[$key]['answer'] = implode(',',$user_answer_arr);
                    if(count($result) == count($answer_arr)){
                        $answers[$key]['correct'] = 1;
                        $total_score = $total_score + $val['score'];
                        $total_right++;
                    }else{
                        $answers[$key]['correct'] = 0;
                    }	
                }else{
                    //未答题，直接错误
                    $total_noanswer++;
                    $answers[$key]['correct'] = 0;
                    $answers[$key]['answer'] = '';
                }
            }
            //插入 用户答题表   createtime=unix_timestamp(now())
            $answers = json_encode($answers);
            $sql = "insert into fa_test_user(test_id,mobile,answers,score,status,createtime) 
                    values($testId,'$mobile','$answers',$total_score,1,unix_timestamp(now())) ";
            Db::execute($sql);
                              
            // 增加积分（更新：积分记录表 + 用户表）
            $scoreRes = $this->_addUserScore($mobile,$total_score,$testId,$dateInfo,'答题');
            if ($scoreRes["code"] == 200) {
                $sql = "select score from fa_user where mobile='$mobile'";
                $sqlRes = Db::query($sql);
                $data["score"] =  $sqlRes[0]["score"];
                $data["currentScore"] =  $total_score;
                Db::commit();
                return $this->success("success", $data, 200);
            }
            // 出错，回滚
            Db::rollback();
            return $this->success("fail", null, 400);
        } catch (PDOException $e) {
            Db::rollback();
            return $this->success("试卷提交异常" . $e->getMessage(), null, 500);
        }
    }
    
    //-------------------------------------------我的-------------------------------------------------------
    // 建议反馈
    public function addAdvise()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        $content = $params["content"] ?? null;
        $title = $params["title"] ?? null;
        $questionType = $params["questionType"] ?? null;
        if (!($mobile && $content && $title)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            $sql = "INSERT INTO `fa_advise` set mobile='$mobile',questiontype='$questionType', title='$title', content='$content',createtime=unix_timestamp(now())";
            Db::execute($sql);
            return $this->success("提交成功", null, 200);
        } catch (PDOException $e) {
            return $this->success("提交失败" . $e->getMessage(), null, 500);
        }
    }

    // 修改密码
    public function changePassword()
    {
        $params = $this->request->param();
        $oldPassword = $params["oldPassword"] ?? null;
        $newPassword = $params["newPassword"] ?? null;
        $confirmPassword = $params["newPassword"] ?? null;
        $mobile = $params["mobile"] ?? null;
        if (!($mobile && $oldPassword)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            $sql = "SELECT password, salt FROM `fa_user` WHERE mobile='$mobile'";
            $sqlRes = Db::query($sql);
            $pwd = $sqlRes[0]["password"];
            $salt = $sqlRes[0]["salt"];
            if (count($sqlRes) == 0) {
				return $this->success("没有该用户", null, 400);
            }
            if (md5(md5($oldPassword) . $salt) != $pwd) {
                return $this->success("密码错误", null, 400);
            }
            if($newPassword != $confirmPassword){
                return $this->success("两次密码输入不一致", null, 400);
            }
            $changePwd = md5(md5($newPassword).$salt);
            $sql = "UPDATE fa_user SET password ='$changePwd' WHERE mobile='$mobile'";
            Db::execute($sql);
            return $this->success("修改成功", null, 200);
          
        } catch (PDOException $e) {
            return $this->success("密码修改失败" . $e->getMessage(), null, 500);
        }
    }
    
    // 修改用户信息
    public function changeUserInfo()
    {
        $params = $this->request->param();
        $mobile = $params["mobile"] ?? null;
        if (!($mobile)) {
            return $this->success("参数不全", null, 400);
        }
        try {
            // todo...

            return $this->success("success", null, 200);
        } catch (PDOException $e) {
            return $this->success("修改用户信息出错" . $e->getMessage(), null, 500);
        }
    }

     // 获取用户积分列表
     public function getScoreList()
     {
         $params = $this->request->param();
         $mobile = $params["mobile"] ?? null;
         if (!($mobile)) {
             return $this->success("参数不全", null, 400);
         }
         try {
             $sql = "SELECT item,itemtype,score,dateinfo FROM `fa_user_score_record` WHERE mobile='$mobile'";
             $sqlRes = Db::query($sql);
             return $this->success("success", $sqlRes, 200);
           
         } catch (PDOException $e) {
             return $this->success("获取用户积分列表失败" . $e->getMessage(), null, 500);
         }
     }
    
}
